﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMathLibrary
{
    /// <summary>
    /// This class represents a Newton polynomial.
    /// </summary>
    [Serializable]
    public class NewtonPolynomial : AbstractRealPolynomial, INewtonPolynomial, IRealFunction
    {
        /// <summary>
        /// The coefficients of the polynomial.
        /// </summary>
        private readonly double[] coefficients;

        /// <summary>
        /// The x values of the polynomial.
        /// </summary>
        private readonly double[] xValues;

        /// <summary>
        /// The constant value of the polynomial.
        /// </summary>
        private double constantValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="NewtonPolynomial"/> class.
        /// </summary>
        /// <param name="coefficients">The coefficients of the polynomial.</param>
        /// <param name="xValues">The x values of the polynomial.</param>
        /// <param name="constantValue">The constant value of the polynomial.</param>
        public NewtonPolynomial(double[] coefficients, double[] xValues, double constantValue)
        {
            if (xValues == (double[]) ((object) null))
            {
                throw new ArgumentNullException("xValues");
            }

            if (coefficients == (double[]) ((object) null))
            {
                throw new ArgumentNullException("coefficients");
            }

            if (xValues.Length != coefficients.Length)
            {
                throw new Exception("The number of x values has to be even with the number of coefficients.");
            }

            this.constantValue = constantValue;
            this.coefficients = (double[]) coefficients.Clone();
            this.xValues = (double[]) xValues.Clone();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NewtonPolynomial"/> class.
        /// </summary>
        /// <param name="polynomial">The polynomial to clone.</param>
        public NewtonPolynomial(NewtonPolynomial polynomial)
        {
            if (polynomial == (NewtonPolynomial) null)
            {
                throw new ArgumentNullException("polynomial");
            }

            this.constantValue = polynomial.ConstantValue;
            this.coefficients = (double[]) polynomial.Coefficients.Clone();
            this.xValues = (double[]) polynomial.XValues.Clone();
        }

        /// <summary>
        /// Gets the coefficients of the polynomial.
        /// </summary>
        /// <value>The coefficients of the polynomial.</value>
        public double[] Coefficients
        {
            get { return coefficients; }
        }

        /// <summary>
        /// Gets the x values of the polynomial.
        /// </summary>
        /// <value>The x values of the polynomial.</value>
        public double[] XValues
        {
            get { return xValues; }
        }

        /// <summary>
        /// Gets or sets the constant value of the polynomial.
        /// </summary>
        /// <value>The constant value of the polynomial.</value>
        public double ConstantValue
        {
            get { return constantValue; }
            set { constantValue = value; }
        }

        /// <summary>
        /// Compares the current instance to the specified polynomial.
        /// </summary>
        /// <param name="compare">The polynomial to compare.</param>
        /// <returns>True if both polynomials are even otherwise, false.</returns>
        public bool CompareTo(NewtonPolynomial compare)
        {
            return (this == compare);
        }

        /// <summary>
        /// Solves the polynomial at the specified position x.
        /// </summary>
        /// <param name="x">The value for evaluation.</param>
        /// <returns>The result f(x) at the specified position x.</returns>
        public override double SolveAt(double x)
        {
            double result = this.constantValue;

            for (int i = 0; i < this.xValues.Length; i++)
            {
                double tempuri = 1;

                for (int j = 0; j <= i; j++)
                {
                    tempuri *= x - this.xValues[j];
                }

                result += tempuri * this.coefficients[i];
            }

            return result;
        }

        /// <summary>
        /// Converts the Newton polynomial to a normal polynomial.
        /// </summary>
        /// <returns>The converted polynomial.</returns>
        public SimplePolynomial ToPolynomial()
        {
            List<SimplePolynomial> workingPolynomials = new List<SimplePolynomial>();

            for (int i = 0; i < this.xValues.Length; i++)
            {
                LinearFactorCollection linearFactors = new LinearFactorCollection();

                for (int j = 0; j <= i; j++)
                {
                    linearFactors.Add(new LinearFactor(-this.xValues[j]));
                }

                if (linearFactors.Count > 1)
                {
                    workingPolynomials.Add(linearFactors.MultiplyFactors());
                }
                else
                {
                    workingPolynomials.Add(linearFactors[0].ToPolynomial());
                }
            }

            SimplePolynomial result = new SimplePolynomial(this.xValues.Length);

            for (int i = 0; i < workingPolynomials.Count; i++)
            {
                workingPolynomials[i].MultiplyWithScalar(this.coefficients[i]);
                result += workingPolynomials[i];
            }

            result.SetValueAtRank(0, result.ValueAtRank(0) + this.constantValue);
            result.RemoveLeadingZeros();

            return result;
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="a">The first NewtonPolynomial.</param>
        /// <param name="b">The second NewtonPolynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(NewtonPolynomial a, NewtonPolynomial b)
        {
            if (System.Object.ReferenceEquals(a, b))
            {
                return true;
            }

            if (((object) a == null) || ((object) b == null))
            {
                return false;
            }

            return (Arrays.Compare(a.Coefficients, b.Coefficients)
                    && Arrays.Compare(a.XValues, b.XValues) && (a.ConstantValue == b.ConstantValue));
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="a">The first NewtonPolynomial.</param>
        /// <param name="b">The second NewtonPolynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(NewtonPolynomial a, NewtonPolynomial b)
        {
            return !(a == b);
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            String result = this.constantValue.ToString();

            for (int i = 0; i < this.xValues.Length; i++)
            {
                result += " + " + this.coefficients[i].ToString();

                for (int j = 0; j <= i; j++)
                {
                    if (this.xValues[j] < 0)
                    {
                        result += "(x + " + Math.Abs(this.xValues[j]) + ")";
                    }
                    else
                    {
                        result += "(x - " + Math.Abs(this.xValues[j]) + ")";
                    }
                }
            }

            return result;
        }
    }
}